package yyy.ab.common.cfgBean;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import yyy.ab.common.utils.DateUtils;
import yyy.ab.common.utils.SecurityUtils;

import java.sql.Timestamp;
import java.util.Date;

/**
 * Mybatis-Plus 审计配置
 */
@Configuration
public class AuditorConfig {

    @Bean
    public AuditMetaObjectHandler auditMetaObjectHandler(){
        return new AuditMetaObjectHandler();
    }
}

class AuditMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        boolean createTime = metaObject.hasSetter("createTime");
        boolean updateTime = metaObject.hasSetter("updateTime");
        if (createTime || updateTime) {
            Timestamp now = DateUtils.getNow();
            if (createTime) {
                this.setFieldValByName("createTime", now, metaObject);
            }
            if (updateTime) {
                this.setFieldValByName("updateTime", now, metaObject);
            }
        }
        String username = "";
        if (metaObject.hasSetter("createBy") || metaObject.hasSetter("updateBy")) {
            username = SecurityUtils.getCurrentUsername();//获取用户，如果使用SpringSecurity的话可以从SecurityContext中获取
        }
        if (metaObject.hasSetter("createBy")) {
            this.setFieldValByName("createBy", username, metaObject);
        }
        if (metaObject.hasSetter("updateBy")) {
            this.setFieldValByName("updateBy", username, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasSetter("updateTime")) {
            this.setFieldValByName("updateTime", DateUtils.getNow(), metaObject);
        }
        if (metaObject.hasSetter("updateBy")) {
            String username = SecurityUtils.getCurrentUsername();//获取用户，如果使用SpringSecurity的话可以从SecurityContext中获取
            this.setFieldValByName("updateBy", username, metaObject);
        }
    }
}


